import { useMemo } from "react";
import { useMutation, useQuery, useQueryClient } from "react-query";
import { useHttp } from "utils/http";

import { useUrlQueryParam } from "utils/url";
import { Label } from "types/label";

export const useLabelSearchParams = () => {
  const [param, setParam] = useUrlQueryParam(["title", "id"]);
  return [
    useMemo(() => ({ ...param, id: Number(param.id) || undefined }), [param]),
    setParam,
  ] as const;
};

export const useLabels = (param?: Partial<Label>) => {
  const client = useHttp();

  return useQuery<Label[]>(["labels", param], () =>
    client("label/lists", { data: param })
  );
};

export const useLabelParam = () => {
  const [{ id }] = useUrlQueryParam(["id"]);
  const { data: label, isLoading } = useLabel(Number(id));

  return {
    id,
    label,
    isLoading,
  };
};

export const useLabel = (id?: number) => {
  const client = useHttp();
  return useQuery<Label>(
    ["label", { id }],
    () => client(`label/detail/${id}`),
    {
      enabled: !!id,
    }
  );
};

interface QiniuToken {
  token: string | undefined;
  key: string | undefined;
  qiniu_url_prefix: string | undefined;
}

export const useQiniu = () => {
  const client = useHttp();
  return useQuery<QiniuToken>(["qiniu"], () => client(`label/qiniu`));
};

export const useAddLabel = () => {
  const client = useHttp();
  const queryClient = useQueryClient();
  return useMutation(
    (params: Partial<Label>) =>
      client(`label/add`, { data: params, method: "POST" }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries();
      },
    }
  );
};

export const useModifyLabel = () => {
  const client = useHttp();
  const queryClient = useQueryClient();
  return useMutation(
    (params: Partial<Label>) =>
      client(`label/modify`, {
        data: params,
        method: "POST",
      }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries();
      },
    }
  );
};

export const useLabelDel = (param?: Partial<Label>) => {
  const client = useHttp();
  const queryClient = useQueryClient();
  return useMutation(
    (params: Partial<Label>) =>
      client(`label/del`, {
        data: params,
        method: "POST",
      }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries();
      },
    }
  );
};
